package com.coolingme.general;

import java.util.ArrayList;
import java.util.List;

/**
 * 具体主题：具体被观察者，当其内部发生变化时，会通知已注册的观察者
 *
 * @author wangyue
 * @date 2020-10-01 23:02
 */
public class ConcreteSubject<E> implements ISubject<E> {

    /**
     * 观察者容器
     */
    private List<IObserver<E>> observerList = new ArrayList<>();

    @Override
    public boolean attach(IObserver<E> observer) {
        return !this.observerList.contains(observer) && this.observerList.add(observer);
    }

    @Override
    public boolean detach(IObserver<E> observer) {
        return this.observerList.remove(observer);
    }

    @Override
    public void notify(E event) {
        // 更新状态
        for (IObserver<E> observer : observerList) {
            observer.update(event);
        }
    }
}
